package main

import (
	"fmt"
	"sync"
	"time"
)

var (
	myMap = make(map[int]uint, 10)
	// sync全称: synchronized
	// Mutex 互斥
	lock sync.Mutex
)

func main() {
	for i := 1; i <= 20; i++ {
		go CalculateFactorial(i)
	}

	time.Sleep(time.Second * 10)

	// 如果不加锁，底层还认为有资源竞争
	lock.Lock()
	for i, v := range myMap {
		fmt.Printf("map[%d]=%d\n", i, v)
	}
	lock.Unlock()

}

func CalculateFactorial(num int) {
	var res uint = 1
	for i := 1; i <= num; i++ {
		res *= uint(i)
	}
	lock.Lock()
	myMap[num] = res
	lock.Unlock()
}
